package com.innovation.ic.b1b.monitor.web.config;

import com.innovation.ic.b1b.monitor.base.value.ShardingConfig;
//import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
//import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

@Configuration
public class DatabaseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    private ShardingConfig shardingConfig;

    public DatabaseShardingAlgorithm() {
    }

    public DatabaseShardingAlgorithm(ShardingConfig shardingConfig) {
        this.shardingConfig = shardingConfig;
    }

    /**
     * 插入记录时，决定将记录插入到哪个数据库
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames,
                             PreciseShardingValue<Long> shardingValue) {
        long res = 0 ;
        for (String each : availableTargetNames) {
            res = shardingValue.getValue() ;
            res = res % shardingConfig.getDatabaseNumber().intValue();
            if (each.endsWith(res + "")) {
                return each;
            }
        }
        throw new UnsupportedOperationException();
    }
}
